var data = require('/modules/index/data.js');
var cache = require('/modules/index/cache.js');

init();

function init() {

    updateConsumer(function () {

        var consumer = cache.getConsumer();
        if (consumer !== undefined && consumer !== null) {

            $('#' + consumer).siblings().removeClass('active');
            $('#' + consumer).addClass('active');

            updateTopic(consumer, function () {

                var topic = cache.getTopic();
                if (topic !== undefined && topic !== null) {
                    $('#' + topic).siblings().removeClass('active');
                    $('#' + topic).addClass('active');

                    updatePartition(consumer, topic);
                }

            });
        }
    });


    $('.consumers > ul').on('click', 'li', function () {

        var consumer = this.id;
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        cache.setConsumer(consumer);

        updateTopic(consumer);


    });

    $('.topics > ul').on('click', 'li', function () {

        var topic = this.id;
        var consumer = $(this).attr('data-consumer');
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
        cache.setTopic(topic);

        updatePartition(consumer, topic);
    });

}

function updateConsumer(callback) {

    data.loadConsumers().then(function (resp) {

        if (resp.hasOwnProperty('status') && resp.status === 0) {
            var html = '';
            var consumers = resp.data || [];
            consumers = consumers.sort();
            var html = '';

            for (var i = 0; i < consumers.length; i++) {
                var consumer = consumers[i];
                if (consumer.length === 36 && consumer.split('-').length === 5) {
                    continue;
                }
                html += '<li id="' + consumer + '" class="list-group-item">' + consumer + '</li>';
            }
            $('.consumers > ul').empty().append(html);
            callback && callback();
        } else {
            alert('consumers load failed!');
        }

    });
}

function updateTopic(consumer, callback) {
    $('.topics > ul').empty();
    $('.partitions tbody').empty();
    $('.partitions .logSize').text('LogSize');
    $('.partitions .offset').text('LogSize');
    $('.partitions .lag').text('LogSize');
    data.loadConsumerTopics(consumer).then(function (resp) {
        if (resp.hasOwnProperty('status') && resp.status === 0) {
            var html = '';
            var topics = resp.data || [];
            topics.sort();
            var html = '';
            for (var i = 0; i < topics.length; i++) {
                html += '<li id="' + topics[i] + '" data-consumer="' + consumer + '"  class="list-group-item">' + topics[i] + '</li>';
            }
            $('.topics > ul').empty().append(html);
            callback && callback();
        } else {
            alert('topics load failed!');
        }
    });
}

function updatePartition(consumer, topic) {

    $('.partitions tbody').empty();
    $('.partitions .logSize').text('LogSize');
    $('.partitions .offset').text('Offset');
    $('.partitions .lag').text('Lag');

    data.loadConsumerTopicPartitions(consumer, topic).then(function (resp) {
        if (resp.hasOwnProperty('status') && resp.status === 0) {
            var partitions = resp.data || [];
            partitions.sort(function (a, b) {
                return a.partition - b.partition;
            })
            var html = '';
            var topicLogSize = 0, topicOffset = 0, topicLag = 0;
            for (var i = 0; i < partitions.length; i++) {

                var partition = partitions[i];
                var offset = partition.offset;
                var lastOffset = partition.lastOffset;
                var lastCommitTime = partition.lastCommitTime;
                var lag = 0;

                if (lastOffset === -1 || offset === -1 || topicLogSize === -1 || topicOffset === -1) {
                    topicLogSize = -1;
                    topicOffset = -1;
                    lag = -1;
                } else {
                    topicLogSize += lastOffset;
                    topicOffset += offset;
                    lag = lastOffset - offset;
                }


                html += ('<tr><td>' + partition.partition + '</td>' +
                '<td>' + lastOffset + '</td>' +
                '<td>' + offset + '</td>' +
                '<td>' + lag + '</td>' +
                '<td>' + (lastCommitTime === -1 ? -1 : formatDate(new Date(lastCommitTime))) + '</td>' +
                '<td>' + (partition.owner || '') + '</td></tr>');
            }

            if (topicLogSize === -1 || topicOffset === -1) {
                topicLag = -1;
            } else {
                topicLag = topicLogSize - topicOffset;
            }


            $('.partitions tbody').append(html);
            $('.partitions .logSize').text('LogSize (' + topicLogSize + ')');
            $('.partitions .offset').text('Offset (' + topicOffset + ')');
            $('.partitions .lag').text('Lag (' + topicLag + ')');
        } else {
            alert('partitions load failed!');
        }
    });
}

function formatDate(date, format) {
    date = date || new Date();
    if (typeof date === "string") {
        date = new Date(date);
    }
    format = format || "yyyy-MM-dd HH:mm:ss";
    var v = {};
    var yyyy = v.yyyy = date.getFullYear() + "";
    v.yy = yyyy.substr(2, 2);
    var M = v.M = date.getMonth() + 1;
    v.MM = M >= 10 ? M : "0" + M;
    var d = v.d = date.getDate();
    v.dd = d >= 10 ? d : "0" + d;
    var H = v.H = date.getHours();
    v.HH = H >= 10 ? H : "0" + H;
    var m = v.m = date.getMinutes();
    v.mm = m >= 10 ? m : "0" + m;
    var s = v.s = date.getSeconds();
    v.ss = s >= 10 ? s : "0" + s;
    v.S = date.getMilliseconds();
    var keys = Object.keys(v).sort().reverse();
    var str = format;
    for (var i = 0, key = keys[0]; i < keys.length; key = keys[++i]) {
        while (str.search(key) >= 0) {
            str = str.replace(key, v[key]);
        }
    }
    return str;
}